<script setup>
import { ref, onMounted, computed } from 'vue'
import { getBankList, deleteBank } from '@/api/bank'
import { ElMessage, ElPopconfirm } from 'element-plus'
import logger from '@/utils/logger'
import AddBank from './components/AddBank.vue'
import { getBankInfoByCardNumber } from '@/constants/bank'
import { View, Hide } from '@element-plus/icons-vue'

const bankList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const currentBank = ref(null)
const cardVisibility = ref({})

const isEdit = computed(() => !!currentBank.value?.dealerBankId)
const dialogTitle = computed(() => (isEdit.value ? '编辑银行账户' : '添加银行账户'))

const fetchBankList = async () => {
  try {
    loading.value = true
    const res = await getBankList()
    if (res.success) {
      bankList.value = res.data || []
    } else {
      ElMessage.error(res.msg || '获取银行列表失败')
      bankList.value = []
    }
  } catch (error) {
    logger.error('获取银行列表失败', error)
    ElMessage.error('获取银行列表失败')
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  currentBank.value = null
  dialogVisible.value = true
}

const handleEdit = (row) => {
  currentBank.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = async (dealerBankId) => {
  try {
    const res = await deleteBank(dealerBankId)
    if (res.success) {
      ElMessage.success('删除成功')
      fetchBankList()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    logger.error('删除失败', error)
    ElMessage.error('删除失败')
  }
}

const handleSuccess = () => {
  dialogVisible.value = false
  fetchBankList()
}

const formatBankCode = (code, visible) => {
  if (!code) return ''
  if (visible) {
    // Add space every 4 digits for readability
    return code.replace(/(.{4})/g, '$1 ').trim()
  }
  const visiblePart = code.slice(-4)
  const hiddenPart = '**** **** **** '
  return hiddenPart + visiblePart
}

const toggleVisibility = (id) => {
  cardVisibility.value[id] = !cardVisibility.value[id]
}

onMounted(() => {
  fetchBankList()
})
</script>

<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" destroy-on-close>
    <AddBank :bank-data="currentBank" @success="handleSuccess" @cancel="dialogVisible = false" />
  </el-dialog>

  <div class="main-container">
    <div class="controller-container">
      <div class="controller-item">
        <el-button type="primary" @click="handleAdd">
          <template #icon>
            <el-icon><LineMdPlus /></el-icon>
          </template>
          添加银行账户
        </el-button>
      </div>
    </div>
    <div class="cards-container" v-loading="loading">
      <div
        v-for="bank in bankList"
        :key="bank.dealerBankId"
        class="bank-card"
        :style="{ backgroundColor: getBankInfoByCardNumber(bank.bankCode).color }"
      >
        <div class="card-header">
          <div class="bank-info">
            <img
              :src="getBankInfoByCardNumber(bank.bankCode).logo"
              alt="bank-logo"
              class="bank-logo"
              v-if="getBankInfoByCardNumber(bank.bankCode).logo"
            />
            <span class="bank-name">{{ getBankInfoByCardNumber(bank.bankCode).name }}</span>
          </div>
          <div class="card-actions">
            <el-button
              type="primary"
              circle
              size="small"
              @click="handleEdit(bank)"
              class="action-btn"
            >
              <el-icon><LineMdEdit /></el-icon>
            </el-button>
            <el-popconfirm
              title="确定要删除这个银行账户吗？"
              @confirm="handleDelete(bank.dealerBankId)"
              confirm-button-text="确定"
              cancel-button-text="取消"
              width="250"
            >
              <template #reference>
                <el-button type="danger" circle size="small" class="action-btn">
                  <el-icon><LineMdTrash /></el-icon>
                </el-button>
              </template>
            </el-popconfirm>
          </div>
        </div>
        <div class="card-body">
          <div class="card-number">
            <span>{{ formatBankCode(bank.bankCode, cardVisibility[bank.dealerBankId]) }}</span>
            <el-icon class="eye-icon" @click="toggleVisibility(bank.dealerBankId)">
              <component :is="cardVisibility[bank.dealerBankId] ? View : Hide" />
            </el-icon>
          </div>
        </div>
        <div class="card-footer">
          <span class="card-holder-name">{{ bank.bankName }}</span>
          <el-tag :type="bank.status === 0 ? 'success' : 'info'" size="small">{{
            bank.status === 0 ? '启用' : '禁用'
          }}</el-tag>
        </div>
      </div>
      <el-empty
        v-if="!bankList.length && !loading"
        description="暂无银行卡，请添加"
        class="empty-center"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;
  .controller-container {
    border-radius: 10px;
    background-color: #fff;
    padding: 10px;
    .controller-item {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }
  .cards-container {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    padding: 10px;
    background-color: #fff;
    border-radius: 10px;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 20px;
    align-content: start;
  }

  .bank-card {
    color: white;
    padding: 20px;
    border-radius: 15px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 180px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    transition:
      transform 0.3s,
      box-shadow 0.3s;
    position: relative;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;

      .bank-info {
        display: flex;
        align-items: center;
        gap: 10px;
        .bank-logo {
          width: 32px;
          height: 32px;
          border-radius: 50%;
          background: white;
          padding: 2px;
        }
        .bank-name {
          font-size: 16px;
          font-weight: bold;
        }
      }

      .card-actions {
        display: flex;
        gap: 8px;
        .action-btn {
          background-color: rgba(255, 255, 255, 0.2);
          border: none;
          color: white;
          &:hover {
            background-color: rgba(255, 255, 255, 0.4);
          }
        }
      }
    }

    .card-body {
      text-align: center;
      .card-number {
        font-family: 'Courier New', Courier, monospace;
        font-size: 20px;
        letter-spacing: 2px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;

        .eye-icon {
          cursor: pointer;
          font-size: 18px;
        }
      }
    }

    .card-footer {
      display: flex;
      justify-content: space-between;
      align-items: flex-end;
      font-size: 14px;
      .card-holder-name {
        font-weight: 500;
      }
    }
  }
}
</style>

<style lang="scss" scoped>
.empty-center {
  grid-column: 1 / -1;
  justify-self: center;
  align-self: center;
  height: 100%;
  display: flex;
  align-items: center;
}
</style>
